{% extends 'layout/manage.html' %}
{% load static %}

{% block css %}
    <style>
        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default > .panel-heading a {
            text-decoration: none;
        }

        .panel-default > .panel-heading span {
            padding: 0 5px;
        }
        .panel-default > .panel-heading .function .upload{
            overflow: hidden;
            position: relative;
        }
        .panel-default > .panel-heading .function .upload input {
            opacity: 0;
            position: absolute;
            top: 0px;
            bottom: 0px;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }
        .upload-progress{
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }
        .upload-progress .progress-error {
            color: red;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="container-fluid">
        <div class="panel panel-default" style="margin-top: 30px">
            <div class="panel-heading">
                <div>
                    <a href="{% url 'web:file' project_id=request.tracer.project.id %}">
                        <i class="fa fa-home" aria-hidden="true"></i>
                        <span>文件库</span>
                    </a>
                    {% for bread in breadcrumb_list %}
                        <a href="{% url 'web:file' project_id=request.tracer.project.id %}?folder={{ bread.id }}">
                            <i class="fa fa-caret-right" aria-hidden="true"></i>
                            <span>{{ bread.name }}</span>
                        </a>
                    {% endfor %}

                </div>
                <div class="function">
                    <div class="btn btn-primary btn-xs upload">
                        <div><i class="fa fa-upload"></i> 上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile">
                    </div>
                    <a class="btn btn-success btn-xs" data-toggle="modal" data-target="#addModal" data-whatever="新建文件夹">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i> 新建文件夹
                    </a>
                </div>
            </div>
            <table class="table">
                <thead>
                <tr>
                    <th>名称</th>
                    <th>文件大小</th>
                    <th>更新者</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="rowList">
                    {% for item in file_list %}
                        <tr>
                            <td>
                                {% if item.file_type == 1 %}
                                    <i class="fa fa-file" aria-hidden="true" style="color: #499EF3;"></i>
                                    {{ item.name }}
                                {% else %}
                                    <a href='{% url "web:file" project_id=request.tracer.project.id %}?folder={{ item.id }}'>
                                        <i class="fa fa-folder" aria-hidden="true" style="color: #499EF3;"></i>
                                        {{ item.name }}
                                    </a>
                                {% endif %}
                            </td>
                            <td>
                                {% if item.file_type == 1 %}
                                    {{ item.file_size }}
                                {% else %}
                                    -
                                {% endif %}
                            </td>
                            <td>{{ item.update_user.name }}</td>
                            <td>{{ item.update_time }}</td>
                            <td>
                                {% if item.file_type == 2 %}
                                    <a class="btn btn-default btn-xs" data-toggle="modal" data-target="#addModal"
                                       data-whatever="编辑文件夹" data-name="{{ item.name }}" data-fid="{{ item.id }}">
                                        <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                                    </a>
                                {% else %}
                                    <a href="{% url 'web:file_download' project_id=request.tracer.project.id file_id=item.id %}" class="btn btn-default btn-xs">
                                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                                    </a>
                                {% endif %}
                                <a class="btn btn-danger btn-xs"
                                   data-toggle="modal"
                                   data-target="#delModal"
                                   data-fid="{{ item.id }}"
                                >
                                    <i class="fa fa-trash" aria-hidden="true"></i>
                                </a>
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel"></h4>
                </div>
                <div class="modal-body">
                    <form id="form" novalidate>
                        {% csrf_token %}
                        <input class="hide" type="text" name="fid" id="fid">
                        {% for field in form %}
                            <div class="form-group">
                                <label for="exampleInputEmail1">{{ field.label }}</label>
                                {{ field }}
                                <span class="error-msg">{{ field.errors.0 }}</span>
                            </div>
                        {% endfor %}
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                    <button id="btnFormSubmit" type="button" class="btn btn-primary">确 定</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>确定删除？</h4>
                <p style="padding: 20px 0px;">
                    此操将会删除该文件夹，及其包含的所有文件夹和文件。
                </p>
                <p style="text-align: right;  ">
                    <a class="btn btn-default btn-sm" data-dismiss="modal">取 消</a>
                    <button id="delBtn" type="button" class="btn btn-danger btn-sm">确 定</button>
                </p>
            </div>
        </div>
    </div>

    <!-- 进度条 -->
    <div id="uploadProgress" class="upload-progress hide">
        <div class="panel panel-primary">
            <div class="panel-heading"><i class="fa fa-cloud-upload"> 上传进度</i></div>
        </div>
        <table class="table">
            <tbody id="progressList">

            </tbody>
        </table>
    </div>

    <!--建立文件上传的进度条模板 提供拷贝-->
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress-bar"
                             role="progressbar"
                             aria-valuenow="0"
                             aria-valuemin="0"
                             aria-valuemax="100"
                             style="width: 0;"
                        >
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>

    <!--建立上传成功后要显示模板 提供拷贝-->
    <div class="hide">
        <div id="fileRow">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i>
                    <span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="username"></td>
                <td class="datetime"></td>
                <td>
                    <a href="#" class="btn btn-default btn-xs download">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    </a>
                    <a href="#" class="btn btn-danger btn-xs delete" data-toggle="modal" data-target="#delModal">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        var FORLDER_URL = '{% url "web:file" project_id=request.tracer.project.id %}';
        var DEL_FILE_URL = '{% url "web:file_delete" project_id=request.tracer.project.id %}';
        var COS_CREDENTIAL = '{% url "web:cos_credential" project_id=request.tracer.project.id %}';
        var FILE_POST = '{% url "web:file_post" project_id=request.tracer.project.id %}';
        var CURRENT_FOLDER_ID = "{{ folder_obj.id }}";

        $(function () {
            initAddModal();
            btnFormSubmit();
            delBtn();
            bindUploadFile();
        });

        function initAddModal() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var recipient = button.data('whatever');
                var name = button.data('name');
                var fid = button.data('fid');
                var modal = $(this);
                modal.find('.modal-title').text(recipient);

                // 编辑文件夹
                if (fid) {
                    // 编辑
                    // $('#id_name').val(name)
                    modal.find('#id_name').val(name);
                    modal.find('#fid').val(fid);
                } else {
                    // 新建
                    // 清空信息
                    modal.find('.error-msg').empty();
                    $('#form')[0].reset();
                }
            })

            $('#delModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var fid = button.data('fid');
                // 给按钮添加属性
                $('#delBtn').attr('fid', fid);

            })
        }

        function btnFormSubmit() {
            $('#btnFormSubmit').click(function () {
                $.ajax({
                    url: location.href,
                    type: 'POST',
                    data: $('#form').serialize(),
                    dataType: 'JSON',
                    success: function (res) {

                        if (res.status) {
                            // 刷新页面
                            // location.href：当前浏览器地址栏的url
                            location.href = location.href;
                        } else {
                            $.each(res.error, function (key, value) {
                                $('#id_' + key).next().text(value[0]);
                            });
                        }
                    }
                })
            });
        }

        function delBtn() {
            $('#delBtn').click(function () {
                $.ajax({
                    url: DEL_FILE_URL,
                    type: 'GET',
                    data: {fid: $(this).attr('fid')},
                    success: function (res) {
                        if(res.status){
                            location.href = location.href;
                        }
                    }
                })
            });
        }
        /*
        * 修改逻辑：
        * 把获取凭证放到每次上传文件时，这样才能对文件容量进行限制
        * */
        // 绑定改变事件
        function bindUploadFile() {

            // 临时凭证
            $('#uploadFile').change(function () {
                // 清空上一次上传的内容
                $('#progressList').empty();

                var checkFileList = [];
                var fileList = $(this)[0].files;

                $.each(fileList, function (index, fileObject) {
                    // 把所有的文件都获取
                    checkFileList.push({'name': fileObject.name, 'size': fileObject.size});
                });
                // 上传数据到后台，校验数据，通过则发临时凭证
                // 上传 异步
                var cos_credential = new COS({
                   getAuthorization: function (options, callback) {
                       // 获取临时凭证
                       $.post(COS_CREDENTIAL, JSON.stringify(checkFileList), function (res) {

                           if(res.status){
                               var credentials = res.data && res.data.credentials;
                               if(!res.data || !credentials){
                                   return console.error('credentials invalid');
                               }
                               callback({
                                   TmpSecretId: credentials.tmpSecretId,  // 这里得小写 不是TmpSecretId
                                   TmpSecretKey: credentials.tmpSecretKey,
                                   XCosSecurityToken: credentials.sessionToken,
                                   StartTime: res.data.startTime,
                                   ExpiredTime: res.data.expiredTime,
                               });

                               // 授权后，展示上传进度条的模板
                               $('#uploadProgress').removeClass('hide');
                           }else{
                               alert(res.error);
                           }
                       });
                   }
                });
                $.each(fileList, function (index, fileObject) {

                    var fileName = fileObject.name;
                    var fileSize = fileObject.size;
                    var key = (new Date()).getTime() + '_' + fileName;

                    var tr = $('#progressTemplate').find('tr').clone();
                    tr.find('.name').text(fileName);
                    $('#progressList').append(tr);

                    // 上传 异步
                    cos_credential.putObject({
                        Bucket: '{{ request.tracer.project.bucket }}',
                        Region: '{{ request.tracer.project.region }}',
                        Key: key,
                        Body: fileObject,
                        onProgress: function (progressData) {
                            // 处理上传进度
                            var percent = progressData.percent * 100 + '%';
                            tr.find('.progress-bar').text(percent);
                            tr.find('.progress-bar').css('width', percent);
                        }
                    }, function (err, data) {
                        console.log(err || data);
                        // 上传成功后，提交数据到后端
                        if(data && data.statusCode === 200){

                            $.post(FILE_POST, {
                                name: fileName,
                                key: key,
                                file_size: fileSize,
                                parent: CURRENT_FOLDER_ID, // 当前访问的目录id
                                etag: data.ETag,
                                file_path: data.Location,
                            }, function (res) {
                                // 在页面显示已经成功上传的文件
                                var newTr = $('#fileRow').find('tr').clone();

                                newTr.find('.name').text(res.data.name);
                                newTr.find('.file_size').text(res.data.file_size);
                                newTr.find('.datetime').text(res.data.datetime);
                                newTr.find('.username').text(res.data.username);
                                newTr.find('.delete').attr('data-fid', res.data.id);
                                newTr.find('.download').attr('href', res.data.download_url);

                                $('#rowList').append(newTr);

                                // 删除掉删除了的进度条
                                tr.remove();
                            })

                        }else {
                            tr.find('.progress-error').text('上传失败');
                        }
                    });
                });
            });
        }
    </script>
{% endblock %}